
/**
 * Created by PiaoLiangDeWangRuoNan on 2018/9/30.
 */
import React from 'react';
import { connect } from 'react-redux';
import {Input, message, Button, Checkbox, Modal} from 'antd';
import {messages} from 'share/common';
import 'styles/login/active-account/active-account.scss';
import ActiveAccountService from 'containers/login/components/account-login/active-account/active-account.service';
import PasswordRule from 'components/template/reset-password/password-rule';
import ResetPasswordService from "components/template/reset-password/reset-password.service";
import LoginService from 'containers/login/login.service';
import 'styles/login/login-refactoring-ui.scss'

//默认的密码规则
const DefaultRule = {
  isNeedLowercase: true,
  isNeedNumber: true,
  isNeedSpecialChar: false,
  isNeedUppercase: false,
  maxLength: 32,
  minLength: 6,
};

class ActiveAccount extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      rule: DefaultRule,
      loading: false,//登录模块
      imgLoading: false,//获取验证码的loading
      /*
      找回密码的步骤--
      login登录模块
      phoneEmail输入手机号邮箱模块
      confirmCode输入验证码模块
      newPassword输入新密码模块
      resetThenLogin点击完确认新密码页面渲染出的登录模块
      */
      step: "phoneEmail",
      type: 'phone',//输入是手机号还是邮箱
      phoneNum: null,//输入的手机号或邮箱地址
      phoneCode: null,//获得的验证码
      firstPassword: null,//第一次输入的新密码
      secondPassword: null,//第二次输入的新密码
      codeTime: 60,//验证码倒数的时间
      copyInterval: null,
      visible: false,//汇联易协议
      customVisible: false,//自定义协议
      contact: '',//汇联易协议
      customContactTitle: '',//自定义协议的名称
      customContact: '',//自定义协议内容
      readAgree: false,//阅读并同意
      src: "",//验证码图片路径
      attachmentOID: "",//验证码图片attachmentOID
      verifyCode: null,//button
      tenantOnly: false,
      passwordLoading: false,
    }
  }


  componentWillMount(){
    this.getVerifyCodeImage();
  }

  //获取验证码图片
  getVerifyCodeImage = () => {
    this.setState({
      imgLoading: true,
    });
    ActiveAccountService.getVerifyCodeImage().then(res => {
      let src = "data:image/png;base64," + res.data.image;
      this.setState({
        src: src,
        attachmentOID: res.data.attachmentOID,
        imgLoading: false,
      });
    }).catch(err => {
      this.setState({
        imgLoading: false,
      });
    })
  };

  backLogin = () => {
    clearInterval(this.state.copyInterval);
    this.setState({
      step: "login",
    });
    this.props.parentMessage("login");
  };

  //输入手机号或者邮箱时
  inputPhoneEmailChange = (e) => {
    this.setState({
      phoneNum: e.target.value,
      loading: false,
    });
  };

  //输入验证码时
  inputVerifyCodeChange = (e) => {
    this.setState({
      verifyCode: e.target.value,
      loading: false,
    });
  };

  //输完手机号点击下一步
  inputPhoneEmailNext = () => {
    const {phoneNum, attachmentOID, verifyCode} = this.state;
    let pass = LoginService.testPhoneOrEmail(phoneNum).pass;
    if(pass){
      this.setState({
        loading: true,
      });
      let type = LoginService.testPhoneOrEmail(phoneNum).type;
      ActiveAccountService.getConfirmCode(phoneNum, attachmentOID, verifyCode).then(res => {
            this.setState({
              step: "confirmCode",
              loading: false,
              type,
              codeTime: 60,
            }, () => {
              this.getHuilianyiContact();
              let copyInterval = setInterval(() => {
                let codeTime = this.state.codeTime;
                if (codeTime > 0) {
                  codeTime--;
                  this.setState({
                    codeTime,
                    copyInterval,
                  });
                }
                if (codeTime <= 0) {
                  clearInterval(copyInterval)
                }
              }, 1000);
            });
        }).catch(err => {
        this.getVerifyCodeImage();
        this.setState({
          loading: false,
        })
      });
    }
  };

  //获取汇联易协议
  getHuilianyiContact = () => {
    const {phoneNum} = this.state;
    ActiveAccountService.getHuilianyiContact(phoneNum).then(res => {
      this.setState({
        rule: res.data,
        tenantOnly: res.data.tenantOnly,
      });
      if(res.data.tenantProtocol && res.data.tenantProtocolId){
        this.getCustomContact(res.data.tenantProtocolId)
      }
    })
  };
  //获取自定义协议
  getCustomContact = (id) => {
    ActiveAccountService.getCustomContact(id).then(res => {
      if(res.data.i18n.title && res.data.i18n.title.length){
        res.data.i18n.title.map(item => {
          if(item.language === this.props.language.code){
            this.setState({
              customContactTitle: item.value,
            });
          }
        });
      }
      if(res.data.i18n.content && res.data.i18n.content.length){
        res.data.i18n.content.map(item => {
          if(item.language === this.props.language.code){
            this.setState({
              customContact: item.value,
            });
          }
        });
      }
    })
  };
//输入验证码时
  enterConfirmCodeChange = (e) => {
    this.setState({
      phoneCode: e.target.value,
    });
  };
  //输完验证码点击下一步
  enterConfirmCodeNext = () => {
    this.setState({
      loading: true,
    });
    const {phoneNum, phoneCode} = this.state;
    ActiveAccountService.judgeConfirmCode(phoneNum, phoneCode).then(res => {
      if(res.data.message === 'activate.ok'){
        this.setState({
          loading: false,
          step: "resetThenLogin",
          username: phoneNum,
        });
        this.props.parentMessage("resetThenLogin", phoneNum)
      }else{
        this.setState({
          step: "newPassword",
          loading: false,
        });
        ActiveAccountService.getPasswordRule(phoneNum).then(res =>{
          clearInterval(this.state.copyInterval);
          this.setState({
            rule: res.data,
            loading: false,
          })
        }).catch(res => {
          this.setState({
            loading: false,
          })
        })
      }
    }).catch(res => {
      this.setState({
        loading: false,
      })
    })
  };

//点击确认新密码
  confirmNewPassword = () => {
    const {phoneNum, phoneCode, firstPassword, secondPassword} = this.state;
    if(firstPassword !== secondPassword){
      message.error(messages('login.key14'/*两次输入密码不相同*/));
      this.setState({
        firstPassword: '',
        secondPassword: '',
      })
    }else{
      if (ResetPasswordService.regPasswordByRule(secondPassword, this.state.rule)) {
        this.setState({
          passwordLoading: true,
        });
        ActiveAccountService.confirmNewPassword(phoneNum, phoneCode, secondPassword).then(res => {
          this.setState({
            passwordLoading: false,
            step: "resetThenLogin",
            username: phoneNum,
            firstPassword: '',
            secondPassword: '',
          });
          this.props.parentMessage("resetThenLogin", phoneNum)
        }).catch(res => {
          this.setState({
            passwordLoading: false,
          })
        });
      }
    }
  };

  //第一次输入新密码时
  enterNewPasswordChange = (e) => {
    this.setState({
      firstPassword: e.target.value,
    })
  };

  //再次输入新密码时
  confirmNewPasswordChange = (e) => {
    this.setState({
      secondPassword: e.target.value,
    })
  };
  readAgreeChange=(e)=>{
    this.setState({readAgree: e.target.checked})
  };
  onCustomVisible=(e)=>{
    this.setState({customVisible: true})
  };
  //输入新密码这一步
  enterNewPassword = () => {
    const { firstPassword, secondPassword, passwordLoading} = this.state;
    return (
      <div>
        {this.renderTitle(messages('login.key53')/*创建新密码*/)}
          <PasswordRule rule={this.state.rule}/>
          {/*请输入您的新密码(6-20位的数字英文组合,字母区分大小写)*/}
        <div className="inp-wrap" style={{marginTop: 0}}>
          <Input
            size="large"
            type="password"
            className={"enter-password-input"}
            value={firstPassword}
            placeholder={messages('login.key12'/*请输入新密码*/)}
            onChange={this.enterNewPasswordChange}/>
          <Input
            size="large"
            type="password"
            className={"enter-password-input"}
            value={secondPassword}
            placeholder={messages('login.key13'/*再次输入新密码*/)}
            onChange={this.confirmNewPasswordChange}/>
        </div>
          <Button type="primary"
                  size="large"
                  loading={passwordLoading}
                  className="login-refactoring-btn"
                  style={{width: "100%"}}
                  onClick={this.confirmNewPassword}>
            {messages("common.ok")}
          </Button>
        {this.renderBackLogin()}
      </div>
    )
  };

  //输入验证码这一步
  enterConfirmCode = () => {
    const { codeTime, type, phoneNum, readAgree, customContactTitle, visible, customVisible,
      customContact, phoneCode, tenantOnly,} = this.state;
    let link = this.props.language.code.toLowerCase() === "zh_cn" ? "https://console.huilianyi.com/register/pages/protocol.html"
                : "https://console.huilianyi.com/register/pages/protocol-en.html";
    return (
      <div>
        {this.renderTitle(messages('login.key54')/*输入验证码*/)}
        {/*<span style='color:white'>已向您</span><span style='color: #4B8DFF'>{arg1}</span><span style='color:white'>的{arg2}发送验证码,请注意查收</span>*/}
        <div dangerouslySetInnerHTML={{__html: messages('login.key55',{arg1:phoneNum,arg2:type})/*<span>已向您 {arg1} 的{arg2}发送验证码,请注意查收后在下方输入</span>*/}}
             className={"code-note"}/>
        <div className="inp-wrap">
          <div className="verify-code2">
            <Input size="large"
                   className="verify-code-inp"
                   style={{border: "none"}}
                   placeholder={messages('login.key8'/*请输入验证码*/)}
                   onChange={this.enterConfirmCodeChange}/>
            <div className="verify-code-img">
              {
                codeTime === 0 ?
                  <span className="pointer get-message-code"
                      onClick={this.inputPhoneEmailNext}>
                    {messages('login.key9'/*重新获取*/)}
                  </span>
                : <span className="get-message-code" style={{background: "#D2D2D2"}}>{codeTime}&nbsp;s</span>
              }
            </div>
            <div className="clear"/>
            <div className="login-refactoring-border"/>
          </div>
          <div className="protocol-check-wrap">
            <div className="protocol-check-agree">
              &nbsp;<Checkbox checked={readAgree} onChange={(e) => {this.readAgreeChange(e)}}/>
              <span>{messages('login.key10'/*我已阅读并同意*/)}：
                {
                  tenantOnly ? null :
                    <span className="protocol-check-title" onClick={() => {this.setState({visible: true})}}>
                      {messages('login.key11'/*汇联易用户使用协议*/)}
                    </span>
                }
                {
                  customContactTitle ?
                    <span className="protocol-check-title" onClick={() => {this.onCustomVisible()}}>
                      &nbsp;&nbsp;{customContactTitle}
                    </span>
                    : null
                }
              </span>
            </div>
          </div>
        </div>
          <Button type="primary"
                  size="large"
                  className="login-refactoring-btn"
                  style={{width: "100%"}}
                  loading={this.state.loading}
                  disabled={!readAgree || !phoneCode}
                  onClick={this.enterConfirmCodeNext}>
            {messages('login.key3'/*下一步*/)}
          </Button>
        {this.renderBackLogin()}
        <Modal visible={visible}
               width={780}
               className={"protocol-modal"}
               onCancel={() => {this.setState({visible: false})}}
               footer={null}>
          <iframe src={link}
                  width={730}
                  height={450}
                  style={{border: 'none', marginTop: 30}}/>
        </Modal>
        <Modal  footer={null}
                visible={customVisible}
                onCancel={() => {this.setState({customVisible: false})}}>
          <div dangerouslySetInnerHTML={{__html: customContact}}/>
        </Modal>
      </div>
    )
  };

  enterAccount=()=>{
    const {src, verifyCode} = this.state;
    return (<div>
      {this.renderTitle(messages('login.key1')/*激活账号*/)}
      <div className="inp-wrap">
        <Input size="large"
               className={"enter-password-input"}
               placeholder={messages('login.key2'/*请输入手机号/邮箱*/)}
               onChange={this.inputPhoneEmailChange}/>
        <div className="verify-code">
          <Input size="large"
                 className="verify-code-inp"
                 style={{border: "none"}}
                 placeholder={messages('login.key8'/*请输入验证码*/)}
                 onChange={this.inputVerifyCodeChange}/>
          <div className="verify-code-img">
            {src ? <img src={src}
                        alt={messages('setting.key1502'/*加载失败*/)}
                        onClick={this.getVerifyCodeImage}/>
                : <span>{messages('setting.key1502'/*加载失败*/)}</span>}
          </div>
          <div className="clear"/>
          <div className="login-refactoring-border"/>
        </div>
      </div>
        <Button type="primary"
                size="large"
                className="login-refactoring-btn"
                style={{width: "100%"}}
                disabled={!verifyCode}
                loading={this.state.loading}
                onClick={this.inputPhoneEmailNext}>
          {messages('login.key3'/*下一步*/)}
        </Button>
      {this.renderBackLogin()}
    </div>)
  };

  renderTitle = (text) => {
    return (
      <div className='module-title-text'>
        {text}
      </div>
    )
  };

  renderBackLogin=()=>{
    return (
      <div className="back-login"
           onClick={this.backLogin}>
        {messages('login.key4'/*返回登录*/)}
      </div>
    )
  };

  renderEnter=()=>{
    const {step} = this.state;
    if(step === "phoneEmail"){
      return this.enterAccount();
    }
    if(step === "confirmCode"){
      return this.enterConfirmCode();
    }
    if(step === "newPassword"){
      return this.enterNewPassword();
    }
  };
  render() {
    return (
      <div className="active-account-wrap login-refactoring-ui">
        {this.renderEnter()}
      </div>
    )
  };
}

ActiveAccount.contextTypes = {
  router: React.PropTypes.object,
  parentMessage: React.PropTypes.func,  //传到 account-login 组件
};

function mapStateToProps(state) {
  return {
    language: state.main.language,
    tenant: state.login.tenant
  }
}

export default connect(mapStateToProps)(ActiveAccount);

